import 'dart:async';

import 'package:erp/data/api/notice_api.dart';
import 'package:erp/modules/main/controller.dart';
import 'package:erp/modules/process_center/controller.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';

class IndexController extends GetxController {
  final MainController mainController = Get.find<MainController>();

  PageController get pageController => mainController.pageController;

  var count = 0.obs;

  Timer? timer;

  @override
  void onInit() {
    super.onInit();
    this.startSchedule();
    pageController.addListener(() => pageController.page == 0 ? this.startSchedule() : this.endSchedule());
  }

  void startSchedule() {
    if (this.timer == null) {
      this.timer = Timer.periodic(Duration(seconds: 5), (timer) async {
        var data = await NoticeApi.queryEmpNotice();
        count.value = data;
      });
    }
  }

  void endSchedule() {
    if (this.timer != null) {
      timer!.cancel();
      timer = null;
    }
  }

  void jumpToProcess() {
    var mainController = Get.find<MainController>();
    var flowCenterController = Get.find<FlowCenterController>();
    if (count.value > 0) {
      mainController.pageController.jumpToPage(1);
      flowCenterController.tabController.index = 1;
    } else {
      mainController.pageController.jumpToPage(1);
    }
  }
}
